package com.yangxk.kadmin.web.common.interceptor;

import com.yangxk.kadmin.common.exception.AccessException;
import com.yangxk.kadmin.web.common.AccessLimitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口限流拦截器
 * @author yangxk
 * @date 2019/3/3 14:04
 */
public class LimitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AccessLimitService accessLimitService = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(AccessLimitService.class);
        if (accessLimitService.tryAcquire())
            return true;

        throw new AccessException();
    }
}
